package com.boboPlanet.comm.context;

import com.boboPlanet.comm.entity.po.LoginUserInfoPO;
import com.boboPlanet.comm.enums.PlanetCommCode;
import com.boboPlanet.comm.thread.ThreadMdcUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import java.io.Serializable;

/**
 * @Description: TODO
 * @Author: mis_wu
 * @Date: 2023/2/18
 **/
public class BusinessThreadContextHolder implements Serializable {

    private static final Logger log = LoggerFactory.getLogger(BusinessThreadContextHolder.class);

    private LoginUserInfoPO loginUserInfo;

    private String businessTime;

    private String traceId;

    public static BusinessThreadContextHolder capture() {
        BusinessThreadContextHolder holder = new BusinessThreadContextHolder();
        holder.loginUserInfo = LoginUserContext.getLoginUserInfoPO();
        holder.businessTime = BusinessStartTimeContext.getTimeStr();
        holder.traceId = StringUtils.isBlank(TraceIdContext.getTranceId())?
                MDC.get(PlanetCommCode.COMM_LOG_KEY.getCode()):TraceIdContext.getTranceId();
        return holder;
    }

    public static void clear() {
        LoginUserContext.clear();
        BusinessStartTimeContext.clear();
        TraceIdContext.remove();
        ThreadMdcUtil.remove();
    }

    public void inject() {
        LoginUserContext.mock(this.loginUserInfo);
        BusinessStartTimeContext.mock(this.businessTime);
        TraceIdContext.setTraceId(traceId);
        ThreadMdcUtil.setTraceId(traceId);
    }

}
